package com.situ.shoplook.common.impl;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.situ.shoplook.common.mapper.ShoppingCartMapper;
import com.situ.shoplook.common.mapper.UserMapper;
import com.situ.shoplook.common.model.User;
import com.situ.shoplook.common.service.UserService;
import jakarta.servlet.http.HttpSession;
import org.jasypt.util.password.PasswordEncryptor;
import org.jasypt.util.password.StrongPasswordEncryptor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.ObjectUtils;
import org.springframework.util.StringUtils;

import java.util.List;
import java.util.Map;

/**
 * @Author xinchen
 * @Date: 2024/08/30/ 17:38
 * @Description
 */
@Service
public class UserServiceImpl implements UserService {

    private UserMapper userMapper;

    @Autowired
    private ShoppingCartMapper shoppingCartMapper;

    @Autowired
    private HttpSession session;


    public final static String MALL_USER_SESSION_KEY = "newBeeMallUser";//session中user的key
    @Autowired
    public void setAdminMapper(UserMapper userMapper) {
        this.userMapper = userMapper;
    }
    /**
     * add
     */
    @Override
    public int save(User user) throws Exception {
        User user1 = userMapper.selectByLoginName(user.getLoginName());
        if (!ObjectUtils.isEmpty(user1)) {
            throw new Exception("用户名已存在");
        }

        PasswordEncryptor pe  = new StrongPasswordEncryptor();
        String pass = pe.encryptPassword(user.getPasswordMd5());
        user.setPasswordMd5(pass);
        //设置开启状态
        user.setLockedFlag(0);
        return this.userMapper.insertSelective(user);
    }

    /**
     * 更新
     * @throws Exception
     */
    @Override
    public int update(User user) throws Exception {
        if (StringUtils.hasText(user.getLoginName())){
            User admins = userMapper.selectByLoginName(user.getLoginName());
            if ( ! ObjectUtils.isEmpty(admins) && !user.getUserId().equals(admins.getUserId())) {
                throw new Exception("用户名已存在");
            }
        }
        // 检查密码是否更改
        User originalUser = userMapper.selectByPrimaryKey(user.getUserId());
        if (originalUser != null && !originalUser.getPasswordMd5().equals(user.getPasswordMd5())) {
            // 密码已更改，进行加密
            PasswordEncryptor pe = new StrongPasswordEncryptor();
            String encryptedPassword = pe.encryptPassword(user.getPasswordMd5());
            user.setPasswordMd5(encryptedPassword);
        }
        int count = userMapper.updateByPrimaryKeySelective(user);
        return count;
    }

    /**
     * 删除
     * @return
     */
    @Override
    public int remove(Integer[] ids) {
        int count =  userMapper.deleteByIds(ids);
        System.out.println(count);
        return count;
    }

    /**
     * 分页
     * @return
     */
    @Override
    public PageInfo searchByPage(Integer page, Integer limit, User user)  {
        try(Page<?> __ = PageHelper.startPage(page, limit)) {
            List<User> list = userMapper.search(user);
            PageInfo pageInfo = new PageInfo<>(list);
            return pageInfo;
        }
    }

    /**
     * 登录校验
     * @return
     */
    @Override
    public Map<String, Object> login(String loginName, String password, HttpSession session) {
        User user =  userMapper.selectByLoginName(loginName);
        if (user == null) {
            return Map.of("code", 400, "msg", "用户不存在");
        }
        if (user.getLockedFlag() == 1) {
            return Map.of("code", 400, "msg", "用户被锁定");
        }
        // TODO: 加密处理
        if(!user.getPasswordMd5().equals(password)){
            return Map.of("code", 400, "msg", "密码错误");
        }
        /**
         * 该用户的购物车总数
         */
        int count = this.shoppingCartMapper.findByUserIdCount(user.getUserId());
        /**
         * 颁发令牌 TODO:
         */
        session.setAttribute(MALL_USER_SESSION_KEY, user);
        session.setAttribute("shopCartItemCount", count);
        return Map.of("code", 200, "msg", "登录成功");
    }

    /**
     * 注册业务
     * @return
     */
    @Override
    public Map<String, Object> register(String loginName, String password) {
        User user = this.userMapper.selectByLoginName(loginName);
        if (!ObjectUtils.isEmpty(user)) {
            return Map.of("code", 400, "msg", "用户名已存在");
        }
        user = new User();
        user.setLoginName(loginName);
        // TODO: 加密处理
        user.setPasswordMd5(password);
        user.setNickName(loginName);
        user.setLockedFlag(0);
        int count = this.userMapper.insertSelective(user);
        if (count < 1) {
            return Map.of("code", 400, "msg", "注册失败");
        }
        return Map.of("code", 200, "msg", "注册成功");
    }

    @Override
    public User findById(Long userId) {
        return userMapper.selectByPrimaryKey(userId);
    }
}
